﻿using Newtonsoft.Json;
using PhysicalExamination5.Interface.DataMaintenance;
using PhysicalExamination5.Model.DataMaintenance;
using PhysicalExamination5.Model.PhysicalExamination;
using PhysicalExamination5.Model.SystemSetting;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhysicalExamination5.Service.DataMaintenance
{
    public class SChangJianJieGuoWeiHu : IChangJianJieGuoWeiHu
    {
        private readonly ISqlSugarClient db;
        public SChangJianJieGuoWeiHu(ISqlSugarClient db)
        {
            this.db = db;
        }
        /// <summary>
        /// 查询科室项目
        /// </summary>
        /// <param name="strYuanQu"></param>
        /// <returns></returns>
        public string GetSelItemDataAll(string strYuanQu)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】");

                #region 声明变量

                List<KeShiItemDataTreeClass> listkeShiItemDataTree = new List<KeShiItemDataTreeClass>();
                List<jcsj_KeShi> listjcsj_KeShi = new SqlSugarRepository<jcsj_KeShi>(db).getByWhere(t => t.SuoShuYuanQu.Contains(strYuanQu)).OrderBy(t => t.ShunXu).ToList();
                List<jcsj_ZuHeXiangMu> listjcsj_ZuHeXiangMu = new SqlSugarRepository<jcsj_ZuHeXiangMu>(db).getByWhere(t => t.SuoShuYuanQu.Contains(strYuanQu)).OrderBy(t => t.ShunXu).ToList();
                List<jcsj_MingXiXiangMu> listjcsj_MingXiXiangMu = new SqlSugarRepository<jcsj_MingXiXiangMu>(db).getAll().OrderBy(t => t.ShunXu).ToList();

                #endregion

                #region 准备返回数据

                foreach (var jcsj_KeShi in listjcsj_KeShi)
                {
                    KeShiItemDataTreeClass keShiItemDataTree = new KeShiItemDataTreeClass();
                    keShiItemDataTree.strCode = jcsj_KeShi.KeShiID.ToString();
                    keShiItemDataTree.strName = jcsj_KeShi.KeShiMingCheng.ToString();
                    keShiItemDataTree.strType = jcsj_KeShi.KeShiLeiXing.ToString();
                    var jcsj_ZuHeXiangMues = listjcsj_ZuHeXiangMu.Where(t => t.KeShiID == jcsj_KeShi.KeShiID)
                        .OrderBy(t => t.ShunXu).ToList();
                    List<ItemDataTreeClass> listZuHechildren = new List<ItemDataTreeClass>();
                    foreach (var jcsj_ZuHeXiangMu in jcsj_ZuHeXiangMues)
                    {
                        ItemDataTreeClass ZuHechildren = new ItemDataTreeClass();
                        ZuHechildren.strCode = "_" + jcsj_ZuHeXiangMu.ZuHeXiangMuID.ToString();
                        ZuHechildren.strName = jcsj_ZuHeXiangMu.ZuHeXiangMuMingCheng.ToString();

                        if (jcsj_KeShi.KeShiLeiXing != "彩超科室" || jcsj_KeShi.KeShiLeiXing != "放射科室")
                        {
                            var jcsj_MingXiXiangMues = listjcsj_MingXiXiangMu.Where(t => t.ZuHeXiangMuID == jcsj_ZuHeXiangMu.ZuHeXiangMuID).OrderBy(t => t.ShunXu).ToList();
                            List<ItemDataTreeClass> listMingXichildren = new List<ItemDataTreeClass>();
                            foreach (var jcsj_MingXiXiangMu in jcsj_MingXiXiangMues)
                            {
                                ItemDataTreeClass MingXichildren = new ItemDataTreeClass();
                                MingXichildren.strCode = "|" + jcsj_MingXiXiangMu.MingXiXiangMuID.ToString();
                                MingXichildren.strName = jcsj_MingXiXiangMu.MingXiXiangMuMingCheng.ToString();
                                listMingXichildren.Add(MingXichildren);
                            }
                            ZuHechildren.children = listMingXichildren;
                        }
                        listZuHechildren.Add(ZuHechildren);
                    }
                    if (listZuHechildren.Count != 0)
                    {
                        keShiItemDataTree.children = listZuHechildren;
                        listkeShiItemDataTree.Add(keShiItemDataTree);
                    }
                }

            #endregion



            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = listkeShiItemDataTree
                });
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
        /// <summary>
        /// 查询常见结果
        /// </summary>
        /// <param name="strKeShiId"></param>
        /// <param name="strZuHeItemId"></param>
        /// <param name="strMingXiItemId"></param>
        /// <returns></returns>
        public string GetSelChangJianJieGuo(string strKeShiId, string strZuHeItemId, string strMingXiItemId)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】");

                #region 声明变量

                List<ChangJianJieGuoTreeClass> listchangJianJieGuoTree = new List<ChangJianJieGuoTreeClass>();

                #endregion

                #region 验证数据

                if (string.IsNullOrEmpty(strKeShiId))
                {
                    nret = 0;
                    strFanHuiZhi = "科室ID为空！";
                    goto PROC_EXIT;
                }
                if (string.IsNullOrEmpty(strZuHeItemId))
                {
                    nret = 0;
                    strFanHuiZhi = "组合项目ID为空！";
                    goto PROC_EXIT;
                }
                if (string.IsNullOrEmpty(strMingXiItemId))
                {
                    nret = 0;
                    strFanHuiZhi = "明细项目ID为空！";
                    goto PROC_EXIT;
                }

                #endregion

                #region 查询准备返回数据

                List<jcsj_ChangJianJieGuo> listjcsj_ChangJianJieGuo = new SqlSugarRepository<jcsj_ChangJianJieGuo>(db)
                    .getByWhere(t => t.KeShiID == strKeShiId && t.ZuHeXiangMuID == strZuHeItemId.Replace("_", "") && t.MingXiXiangMuID == strMingXiItemId.Replace("|", ""))
                    .OrderBy(t => t.ShunXu)
                    .ToList();
                listchangJianJieGuoTree = BuildTree(listjcsj_ChangJianJieGuo);

            #endregion

            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = listchangJianJieGuoTree
                });
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
        /// <summary>
        /// 添加常见结果树结点
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public string PostChangJianJieGuoTreeNodeAdd(ChangJianJieGuoTreeNodeClass changJianJieGuoTreeNode, string strYuanQuQianZhui)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】");

                #region 声明变量

                int iShuanXu = 0;
                int itid = 0;

                #endregion

                #region 验证数据

                if (!changJianJieGuoTreeNode.Validate("Add", out strFanHuiZhi)) goto PROC_EXIT;
                if (!new SqlSugarRepository<jcsj_ChangJianJieGuo>(db).getByWhere(t => t.ChangJianJieGuoID == changJianJieGuoTreeNode.strShangJiJieDianId).Any() && changJianJieGuoTreeNode.strShangJiJieDianId != "000")
                {
                    nret = 1;
                    strFanHuiZhi = $@"上级结点【{changJianJieGuoTreeNode.strShangJiJieDianId}】不存在！";
                    goto PROC_EXIT;
                }

                #endregion

                #region 保存结点

                DbResult<bool> result = new SqlSugarRepository<jcsj_WeiHaiYinSuZuHeXiangMu>(db).UseTran(() =>
                {
                    var ShunXu = new SqlSugarRepository<jcsj_ChangJianJieGuo>(db)
                    .getByWhere(t => t.KeShiID == changJianJieGuoTreeNode.strKeShiId && t.ZuHeXiangMuID == changJianJieGuoTreeNode.strZuHeXiangMuId
                    && t.MingXiXiangMuID == changJianJieGuoTreeNode.strMingXiXiangMuId);
                    if (ShunXu.Any())
                    {
                        iShuanXu = ShunXu.Max(t => t.ShunXu) + 1;
                    }
                    else
                    {
                        iShuanXu = 1;
                    }
                    jcsj_ChangJianJieGuo jcsj_ChangJianJieGuo = new jcsj_ChangJianJieGuo();
                    jcsj_ChangJianJieGuo.KeShiID = changJianJieGuoTreeNode.strKeShiId;
                    jcsj_ChangJianJieGuo.ZuHeXiangMuID = changJianJieGuoTreeNode.strZuHeXiangMuId;
                    jcsj_ChangJianJieGuo.MingXiXiangMuID = changJianJieGuoTreeNode.strMingXiXiangMuId;
                    jcsj_ChangJianJieGuo.ChangJianJieGuoMingCheng = changJianJieGuoTreeNode.strChangJianJieGuoName;
                    jcsj_ChangJianJieGuo.ShiFouYangXing = changJianJieGuoTreeNode.strShiFouYangXing;
                    jcsj_ChangJianJieGuo.ShiFouXiaoJie = changJianJieGuoTreeNode.strShiFouXiaoJie;
                    jcsj_ChangJianJieGuo.ShiFouMoRen = changJianJieGuoTreeNode.strShiFouMoRen;
                    jcsj_ChangJianJieGuo.ShangJiChangJianJieGuoID = changJianJieGuoTreeNode.strShangJiJieDianId;
                    jcsj_ChangJianJieGuo.BiaoXian = changJianJieGuoTreeNode.strBiaoXian;
                    jcsj_ChangJianJieGuo.ZhenDuan = changJianJieGuoTreeNode.strZhenDuan;
                    jcsj_ChangJianJieGuo.ShunXu = iShuanXu;
                    itid = new SqlSugarRepository<jcsj_ChangJianJieGuo>(db).AddReturnIdentity(jcsj_ChangJianJieGuo);
                    jcsj_ChangJianJieGuo.ChangJianJieGuoID = strYuanQuQianZhui + itid;
                    jcsj_ChangJianJieGuo.tid = itid;
                    if (new SqlSugarRepository<jcsj_ChangJianJieGuo>(db).Update(t => new jcsj_ChangJianJieGuo
                    {
                        ChangJianJieGuoID = jcsj_ChangJianJieGuo.ChangJianJieGuoID
                    }, t => t.tid == itid) == false)
                    {
                        nret = 1000;
                        strFanHuiZhi = "保存结点失败！";
                        return;
                    }
                },
                (ex) =>
                {
                    nret = 1000;
                    strFanHuiZhi = ex.Message;
                    Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:事务报错异常:【{ex.Message}】");
                });
               

            #endregion


            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = ""
                });
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
        /// <summary>
        /// 修改常见结果树结点
        /// </summary>
        /// <param name="changJianJieGuoTreeNode"></param>
        /// <returns></returns>
        public string PutChangJianJieGuoTreeNodeUpdate(ChangJianJieGuoTreeNodeClass changJianJieGuoTreeNode)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】");

                #region 验证数据

                if (!changJianJieGuoTreeNode.Validate("Update", out strFanHuiZhi)) goto PROC_EXIT;
                if (new SqlSugarRepository<jcsj_ChangJianJieGuo>(db)
                    .getByWhere(t => t.ChangJianJieGuoID != changJianJieGuoTreeNode.strChangJianJieGuoId
                    && t.KeShiID == changJianJieGuoTreeNode.strKeShiId && t.ZuHeXiangMuID == changJianJieGuoTreeNode.strZuHeXiangMuId
                    && t.MingXiXiangMuID == changJianJieGuoTreeNode.strMingXiXiangMuId
                    && t.ChangJianJieGuoMingCheng == changJianJieGuoTreeNode.strChangJianJieGuoName).Any())
                {
                    nret = 1;
                    strFanHuiZhi = $@"常见结果名称【{changJianJieGuoTreeNode.strChangJianJieGuoName}】已经存在！";
                    goto PROC_EXIT;
                }

                #endregion

                #region 执行修改

                if (new SqlSugarRepository<jcsj_ChangJianJieGuo>(db).Update(t => new jcsj_ChangJianJieGuo
                {
                    ChangJianJieGuoMingCheng = changJianJieGuoTreeNode.strChangJianJieGuoName,
                    ShiFouYangXing = changJianJieGuoTreeNode.strShiFouYangXing,
                    ShiFouXiaoJie = changJianJieGuoTreeNode.strShiFouXiaoJie,
                    ShiFouMoRen = changJianJieGuoTreeNode.strShiFouMoRen,
                    BiaoXian = changJianJieGuoTreeNode.strBiaoXian,
                    ZhenDuan = changJianJieGuoTreeNode.strZhenDuan
                }, t => t.ChangJianJieGuoID == changJianJieGuoTreeNode.strChangJianJieGuoId) == false)
                {
                    nret = 1;
                    strFanHuiZhi = "修改失败！";
                    goto PROC_EXIT;
                }

            #endregion

            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = ""
                });
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
        /// <summary>
        /// 删除常见结果树结点
        /// </summary>
        /// <param name="changJianJieGuoTreeDeleteNode"></param>
        /// <returns></returns>
        public string DeleteChangJianJieGuoTreeNodeDelete(ChangJianJieGuoTreeDeleteNodeClass changJianJieGuoTreeDeleteNode)
        {
            int nret = 0; string strFanHuiZhi = "";
            try
            {
                Logger.Singleton.Debug($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】");

                #region 验证数据

                if (!changJianJieGuoTreeDeleteNode.Validate(out strFanHuiZhi)) goto PROC_EXIT;

                #endregion

                if (new SqlSugarRepository<jcsj_ChangJianJieGuo>(db).DeleteWhere(t => t.ChangJianJieGuoID == changJianJieGuoTreeDeleteNode.strChangJianJieGuoId) == false)
                {
                    nret = 1000;
                    strFanHuiZhi = "删除失败！";
                    goto PROC_EXIT;
                }
                if (new SqlSugarRepository<jcsj_ChangJianJieGuo>(db).Update(t => new jcsj_ChangJianJieGuo
                {
                    ShunXu = t.ShunXu - 1
                },t => t.KeShiID == changJianJieGuoTreeDeleteNode.strKeShiId && t.ZuHeXiangMuID == changJianJieGuoTreeDeleteNode.strZuHeXiangMuId
                    && t.MingXiXiangMuID == changJianJieGuoTreeDeleteNode.strMingXiXiangMuId && t.ShunXu > changJianJieGuoTreeDeleteNode.iShunXu))
                {
                    nret = 1000;
                    strFanHuiZhi = "修改顺序失败！";
                    goto PROC_EXIT;
                }


            PROC_EXIT:
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = nret,
                    Message = strFanHuiZhi,
                    Data = ""
                });
            }
            catch (Exception ex)
            {
                Logger.Singleton.Error($@"【{System.Reflection.MethodBase.GetCurrentMethod().Name}】:报错异常:" + ex.Message);
                return JsonConvert.SerializeObject(new ApiResult<object>()
                {
                    Success = 1000,
                    Message = ex.Message,
                    Data = ""
                });
            }
        }
        /// <summary>
        /// 递归构建树
        /// </summary>
        /// <param name="listjcsj_ChangJianJieGuo"></param>
        /// <param name="strShangJiChangJianJieGuoID"></param>
        /// <returns></returns>
        public static List<ChangJianJieGuoTreeClass> BuildTree(List<jcsj_ChangJianJieGuo> listjcsj_ChangJianJieGuo, string strShangJiChangJianJieGuoID = "000")
        {
            return listjcsj_ChangJianJieGuo
                .Where(d => d.ShangJiChangJianJieGuoID == strShangJiChangJianJieGuoID)
                .Select(node => new ChangJianJieGuoTreeClass
                {
                    strCode = node.ChangJianJieGuoID,
                    strName = node.ChangJianJieGuoMingCheng,
                    strBiaoXian = node.BiaoXian,
                    strZhenDuan = node.ZhenDuan,
                    children = BuildTree(listjcsj_ChangJianJieGuo, node.ChangJianJieGuoID)
                })
                .ToList();
        }
    }
}
